package com.lyz.util;

import java.io.File;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.lyz.config.IConfig;

public class PropertiesUtil implements IConfig{
	
	private final static Logger logger = Logger.getLogger(PropertiesUtil.class);
	
	
	private static PropertiesUtil proUtil = null;
	
	private final String defaultPath = "config/loggerConfig.properties";
	
	private Properties pro = null;
	
	private FileInputStream fis = null;
	
	private String path;
	
	

	
	
	private PropertiesUtil(String filePath){
		
		if(filePath != null){
			path = filePath;
		}else{
			path = defaultPath;
		}
		
			try {
				fis = new FileInputStream(new File(path));
				pro = new Properties();
				pro.load(fis);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (IOException e1){
				e1.printStackTrace();
			}
		
		
	}
	
	public synchronized static PropertiesUtil getInstance(String filePath){
		
		if(proUtil == null){
			proUtil = new PropertiesUtil(filePath);
		}
		return proUtil;
	}
	
	public synchronized static PropertiesUtil getInstance(){
		return getInstance(null);
	}


	public String getProperty(String key){
		
		return pro.getProperty(key);
	}
	
	public void setProperty(String key, String val){
		pro.setProperty(key, val);
	}

	public String getErrorMsg(String name){
		return name+" can not found in config file!";
	}
	
	public String getWarnMsg(String name, String defaultValue){
		return name+" can not found in config file! default value is "+defaultValue;
	}
	
	public int getHotDeployPort(){
		String sPort = pro.getProperty("hotDeployPort");
		if(sPort == null){
			logger.error(getErrorMsg("hotDeployPort"));
		}
		
		return Integer.parseInt(sPort);
	}
	
	/**
	 * 获取过滤器，过滤器目前只用于通过LogSyncerServer接收的数据
	 * @param tag
	 * @return
	 */
	public String getFilter(String tag){
		String filter = pro.getProperty(tag+"Filter");
		if(filter==null || "".equals(filter.trim())){
			logger.warn(getWarnMsg(tag+"Filter", "com.lyz.log.filter.DefaultFilter"));
			return "com.lyz.log.filter.DefaultFilter";
		}
		
		return filter;
	}
	/**
	 * 获取实时性监控的条件，当队列中的值超过过多少时发送警告
	 */
	public String getRealTimeCondition(String tag){
		String con = pro.getProperty(tag+"RealTimeCondition");
		
		if(con == null || "".equals(con.trim())){
			logger.warn(getWarnMsg(tag+"RealTimeCondition", "2"));
			return "2";
		}
		
		return con;
	}

	/**
	 * 获取监控警告级别
	 * @param tag
	 * @return
	 */
	public int getAlertLevel(String tag){
		String sLevel = pro.getProperty(tag+"AlertLevel");
		if(sLevel==null || "".equals(sLevel.trim())){
			/*默认发送邮件*/
			logger.warn(getWarnMsg(tag+"AlertLevel", "sending email(1)"));
			return 1;
		}
		
		return BaseTypeUtil.getInteger(sLevel, 1);
	}
	/**
	 * 标签，只有配置的标签才会启动线程服务
	 * @return
	 */
	public String[] getConfigTags(){
		String sTag = pro.getProperty("configTags");
		if(sTag == null){
			logger.error(getErrorMsg("configTags"));
		}
		return sTag.split(",");
	}
	/**
	 * 获取文件输入流和socket输出流的缓存大小，二者保持一致
	 * @return
	 */
	public int getBytesBufferSize(){
		String size = pro.getProperty("byteBufferSize");
		if(size == null){
			logger.warn(getErrorMsg("byteBufferSize"));
			return 1024;
		}
		return BaseTypeUtil.getInteger(size);
	}
	/**
	 * 进度文件
	 * @param tag
	 * @return
	 */
	public String getProcessingFilePath(String tag){
		
		String filePath = pro.getProperty(tag+"ProcessingFilePath");
		if(filePath == null || "".equals(filePath.trim())){
			filePath = tag+"ProcessingFile.log";
			logger.warn(getErrorMsg(tag+"ProcessingFilePath"));
		}
		
		return filePath;
	}
	
	public String getLogDirectory(String tag){
		
		String dir = pro.getProperty(tag+"LogDir");
		if(dir == null){
			logger.error(getErrorMsg(tag+"LogDir"));
		}
		/*获取动态日期的目录，只针对一天的数据*/
		dir = DynamicDirectoryUtil.getDynamicDirectory(dir);
		
		return dir;
	}
	
	public String getLogDirectory(String tag, java.util.Date date){
		
		String dir = pro.getProperty(tag+"LogDir");
		if(dir == null){
			logger.error(getErrorMsg(tag+"LogDir"));
		}
		/*获取动态日期的目录，只针对一天的数据*/
		dir = DynamicDirectoryUtil.getDynamicDirectory(dir,date);
		
		return dir;
	}
	
	public String getDateFormat(String tag){
		
		String format = pro.getProperty(tag+"DateFormat");
		if(format == null){
			logger.error(getErrorMsg(tag+"DateFormat"));
		}
		
		return format;
	}
	
	public String getFileStart(String tag){
		String start = pro.getProperty(tag+"FileStart");
		if(start == null){
			logger.error(getErrorMsg(tag+"FileStart"));
		}
		
		return start;
	}
	public String getFileEndWith(String tag){
		String end = pro.getProperty(tag+"FileEndWith");
		if(end == null){
			logger.error(tag+"FileEndWith");
		}
		
		return end;
	}
	public String getFileSplit(String tag){
		String split = pro.getProperty(tag+"FileSplit");
		if(split == null){
			logger.error(getErrorMsg(tag+"FileSplit"));
		}
		
		return split;
	}
	/**
	 * 
	 * @return millisecond and value of less than 0 is no timeout
	 */
	public long getFileTimeout(String tag){
		
		String sTimeout = pro.getProperty(tag+"FileTimeout");
		if(sTimeout == null){
			logger.error(getErrorMsg(tag+"FileTimeout"));
		}
		return BaseTypeUtil.getMiliSeconds(sTimeout);
	}
	/**
	 * 服务器的IP地址
	 * @param tag
	 * @return
	 */
	public String getServerIp(String tag){
		String ip = pro.getProperty(tag+"ServerIp");
		if(ip == null){
			logger.error(getErrorMsg(tag+"ServerIp"));
		}
		
		return ip;
	}
	/**
	 * 服务器的IP地址,多个通过逗号分隔
	 * @param tag
	 * @return
	 */
	public String[] getServerIps(String tag){
		String ips = pro.getProperty(tag+"ServerIp");
		
		if(ips == null || "".equals(ips.trim())){
			logger.error(getErrorMsg(tag+"ServerIp"));
		}
		String[] ipArray = ips.split(",");
		
		return ipArray;
	}
	/**
	 * 服务器端口号
	 * @param tag
	 * @return
	 */
	public int getServerPort(String tag){
		String port = pro.getProperty(tag+"ServerPort");
		if(port == null){
			logger.error(getErrorMsg(tag+"ServerPort"));
		}
		
		return Integer.parseInt(port);
	}
	/**
	 * 服务器端口号，多个通过逗号分隔
	 * @param tag
	 * @return
	 */
	public int[] getServerPorts(String tag){
		String ports = pro.getProperty(tag+"ServerPort");
		if(ports == null || "".equals(ports.trim())){
			logger.error(getErrorMsg(tag+"ServerPort"));
		}
		logger.debug(ports);
		String[] sPortArray = ports.split(",");
		int[] portArray = new int[sPortArray.length];
		int i = 0;
		for(; i < sPortArray.length; i++){
			portArray[i] = BaseTypeUtil.getInteger(sPortArray[i], -1);
		}
		logger.debug(portArray[0]+ ":" + portArray[1]);
		return portArray;
	}
	/**
	 * 获取推送服务器的类型
	 * @param tag
	 * @return
	 */
	public String[] getPushServerType(String tag){
		String types = pro.getProperty(tag+"PushServerType");
		if(types == null || "".equals(types.trim())){
			logger.error(getErrorMsg(tag+"PushServerType"));
		}
		
		return types.split(",");
	}
	
	/**
	 * 超过该时间则打印超时日志
	 * @return
	 */
	public int getLogTimeout(){
		String sTimeout = pro.getProperty("logTimeout");
		if(sTimeout == null){
			logger.error(getErrorMsg("logTimeout"));
		}
		
		return BaseTypeUtil.getInteger(sTimeout);
	}
	
	public int getFetchInteval(String tag){
		String sInteval = pro.getProperty(tag+"FetchInteval");
		if(sInteval == null){
			logger.error(getErrorMsg(tag+"FetchInteval"));
		}
		
		return (int)BaseTypeUtil.getMiliSeconds(sInteval);
		
	}
	
	public void storeProperties(){
		try {
			FileWriter writer = new FileWriter(new File(this.path), false);
			pro.store(writer,"");
			writer.close();
		} catch (IOException e) {
			logger.warn("fail to update config file",e);
		}
	}
	/**
	 * 获取器的名称
	 * @param tag
	 * @return
	 */
	public String getFetcherClassName(String tag){
		String className = pro.getProperty(tag+"FetcherClassName");
		if(className == null){
			logger.error(getErrorMsg(tag+"FetcherClassName"));
		}
		return className;
	}
	/**
	 * 获取消息处理类的名称
	 * @param tag
	 * @return
	 */
	public String getMessageHandlerClassName(String tag){
		String className = pro.getProperty(tag+"MessageHandlerClassName");
		if(className == null){
			logger.error(getErrorMsg(tag+"MessageHandlerClassName"));
		}
		return className;
	}
	/**
	 * 消息类型，目前分为字符串(string)和字节数组(bytes)
	 * @return 默认返回字节数组
	 */
	public String getMessageType(String tag){
		String type = pro.getProperty(tag+"MessageType");
		if(type == null){
			logger.error(getErrorMsg(tag+"MessageType"));
			type = this.MSG_TYPE_BYTES;
		}
		
		return type.toLowerCase();
	}
	/**
	 * 获取固定文件的文件名
	 * @param tag
	 * @return
	 */
	public String getFileName(String tag){
		String name = pro.getProperty(tag+"FileName");
		if(name == null){
			logger.error(getErrorMsg(tag+"FileName"));
		}
		
		return name;
	}
	/**
	 *固定文件名的文件第一次获取文件的时间
	 * @param tag
	 * @return
	 */
	public long getFileFirstFetcherTime(String tag){
		String sTime = pro.getProperty(tag+"FileFirstFetcherTime");
		if(sTime == null){
			logger.error(getErrorMsg(sTime));
		}
		
		return BaseTypeUtil.getTime(sTime, "yyyy-MM-dd HH:mm:ss");
	}
	
	/**
	 * 固定文件名的文件获取的间隔时间
	 * @param tag
	 * @return
	 */
	public long getFileFetcherInterval(String tag){
		String sInterval = pro.getProperty(tag+"FileFetcherInterval");
		if(sInterval == null){
			logger.error(getErrorMsg(tag+"FileFetcherInterval"));
		}
		
		return BaseTypeUtil.getMiliSeconds(sInterval);
	}
	/******************************couchbase added 2014.3.12****************************************/
	public String getCouchbaseURI(String tag){
		String uris=pro.getProperty(tag+"CouchbaseURIs");
		if(uris==null){
			logger.error(getErrorMsg(tag+"CouchbaseURIs"));
		}
		return uris;
	}
	
	public String getCouchbaseBucket(String tag){
		String bucket=pro.getProperty(tag+"CouchbaseBucket");
		if(bucket==null){
			logger.error(getErrorMsg(tag+"CouchbaseBucket"));
		}
		return bucket;
	}
	
	public String getCouchbasePassword(String tag){
		String password=pro.getProperty(tag+"Password");
		if(password==null){
			return "";
		}
		return password;
	}
	
	
	/*********************************************mongo db**************************/
	public String getMongodbUrl(String tag){
		
		String url = pro.getProperty(tag+"MongoUrl");
		if(url == null){
			logger.error(getErrorMsg(tag+"MongoUrl"));
		}
		return url;
		
	}
	
	public int getMongodbPort(String tag){
		
		String sPort = pro.getProperty(tag+"MongoPort");
		if(sPort == null){
			logger.error(getErrorMsg(tag+"MongoPort"));
		}
		return Integer.parseInt(sPort);
	}
	
	public String getMongodbUsername(String tag){
		
		String username = pro.getProperty(tag+"MongoUsername");
		if(username == null){
			logger.error(getErrorMsg(tag+"MongoUsername"));
		}
		return username;
	}
	
	public String getMongodbPassword(String tag){
		String password = pro.getProperty(tag+"MongoPassword");
		if(password == null){
			logger.error(getErrorMsg(tag+"MongoPassword"));
		}
		return password;
	}
	
	public String getMongodbSchema(String tag){
		String schema = pro.getProperty(tag+"MongoSchema");
		if(schema == null){
			logger.error(getErrorMsg(tag+"MongoSchema"));
		}
		return schema;
	}
	
	public String getMongodbTable(String tag){
		String table = pro.getProperty(tag+"MongoTable");
		if(table == null){
			logger.error(getErrorMsg(tag+"MongoTable"));
		}
		return table;
	}
	///////////////////////////////////http util/////////////////////////
	public String getUri(String tag){
		String uri = pro.getProperty(tag+"Uri");
		if(uri == null){
			logger.error(getErrorMsg(tag+"Uri"));
		}
		
		return uri;
	}
	/**
	 * 当有多个url的时候调用此方法
	 * @param tag
	 * @return
	 */
	public List<String> getUris(String tag){
		String uri = pro.getProperty(tag+"Uri");
		if(uri == null || "".equals(uri.trim())){
			logger.error(getErrorMsg(tag+"Uri"));
			return null;
		}
		
		String[] uris = uri.split(",");
		List<String> uriList = new ArrayList<String>();
		for(String u : uris){
			if(u==null || "".equals(u.trim())){
				continue;
			}
			uriList.add(u);
		}
		
		return uriList;
	}
	/**
	 * 请求的超时时间
	 * @param tag
	 * @return 默认为3秒
	 */
	public int getSoTimeout(String tag){
		String sTimeout = pro.getProperty(tag+"Sotimeout");
		if(sTimeout == null){
			logger.error(getErrorMsg(tag+"Sotimeout"));
			return 3000;
		}
		
		return (int)BaseTypeUtil.getMiliSeconds(sTimeout);
	}
	
	/**
	 * 获取实际处理发送请求的节点类全名
	 * @param tag
	 * @return
	 */
	public List<String> getTaskNodeNames(String tag){
		String taskNodeName = pro.getProperty(tag+"TaskNodeNames");
		if(taskNodeName == null){
			logger.error(getErrorMsg(tag+"TaskNodeNames"));
			return null;
		}
		String[] tasks = taskNodeName.split(",");
		
		List<String> taskList = new ArrayList<String>();
		/*将数组转换成列表*/
		for(String task : tasks){
			if(task==null || "".equals(task.trim())){
				continue;
			}
			taskList.add(task);
		}
		return taskList;
	}
	/**
	 * 获取随机文件读一行数据的编码方式
	 * @return
	 */
	public String getEncode(){
		
		String encode = pro.getProperty("defaultEncode");
		
		if(encode==null || "".equals(encode.trim())){
			logger.info("default encode is utf-8");
			return "utf-8";
		}
		
		return encode;
	}
	/**
	 * 获取redis服务器的主机地址
	 * @param tag
	 * @return
	 */
	public String getRedisHost(String tag){
		String host = pro.getProperty(tag+"RedisHost");
		if(host==null || "".equals(host.trim())){
			logger.error(getErrorMsg(tag+"RedisHost"));
			return null;
		}
		return host;
	}
	/**
	 * 获取redis的端口
	 * @param tag
	 * @return
	 */
	public int getRedisPort(String tag){
		String sPort = pro.getProperty(tag+"RedisPort");
		int port = BaseTypeUtil.getInteger(sPort, -1);
		if(port < 0){
			logger.error(getErrorMsg(tag+"RedisPort"));
		}
		
		return port;
		
	}
	/**
	 * 获取redis的数据库
	 * @param tag
	 * @return
	 */
	public int getRedisDB(String tag){
		String sDB = pro.getProperty(tag+"RedisDB");
		int db = BaseTypeUtil.getInteger(sDB, -1);
		if(db < 0){
			logger.error(getErrorMsg(tag+"RedisDB"));
		}
		
		return db;
	}
	
	/**
	 * 是否需要每接收一行就进行一次
	 * @param tag
	 * @return
	 */
	public boolean getNeedFlush(String tag){
		String needFlush = pro.getProperty(tag+"NeedFlush");
		if(needFlush == null){
			logger.error(getWarnMsg(tag+"NeedFlush","false"));
			return false;
		}
		if("true".equals(needFlush.trim())){
			return true;
		}
		
		return false;
	}
	/**
	 * 指定客户端的ip地址
	 * @return
	 */
	public String getClientIp(){
		
		String data = pro.getProperty("clientIp");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}

	public String getMailHost() {
		
		String data = pro.getProperty("mailHost");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}

	public String getMailFrom() {
		
		String data = pro.getProperty("mailFrom");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}

	public String getMailTo() {
		
		String data = pro.getProperty("mailTo");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}


	public String getMailUser() {
		String data = pro.getProperty("mailUser");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}


	public String getMailPwd() {
		String data = pro.getProperty("mailPwd");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}

	public String getMsgPhoneNum() {
		
		String data = pro.getProperty("msgPhoneNum");
		
		if(data==null || "".equals(data.trim())){
			return null;
		}
		
		return data;
	}
	
	


}
